﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Beeldbankmvc.Models;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.IO;
using System.Configuration;
using Beeldbankmvc.Code;
using System.Web.Security;


namespace Beeldbankmvc.Models
{
    public partial class ShoppingCart
    {
        BeeldbankLinqDataContext beeldBankDB = new BeeldbankLinqDataContext();
        UserRepository userRep = new UserRepository();


        string shoppingCartId { get; set; }
        public const string CartSessionKey = "CartId";

        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.shoppingCartId = cart.GetCartId(context);
            return cart;
        }

        public void AddToCart(BEELDBANK_MEDIAOBJECT mediaObject, int amount, string type, string size, string finishing, int mediaTypeId)
        {
            var cartItem = beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs.SingleOrDefault(
                c => c.WinkelwagenId == shoppingCartId && c.Type == type && c.Formaat == size && c.Afwerking == finishing &&
                c.MediaId == mediaObject.Id);

            if (cartItem == null)
            {
                // Create a new cart item
                // TODO: fill all the columns when adding an item to the cart
                cartItem = new BEELDBANK_ORDERREGEL_WINKELWAGEN
                {
                    MediaId = mediaObject.Id,
                    WinkelwagenId = shoppingCartId,
                    Aantal = amount,
                    Formaat = size,
                    Type = type,
                    Afwerking = finishing,
                    MediaTypeId = mediaTypeId
                    //createdat = DateTime.Now
                };
                beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs.InsertOnSubmit(cartItem);
            }
            else
            {
                // Add amount to the quantity
                cartItem.Aantal += amount;
            }

            // Save it
            beeldBankDB.SubmitChanges();
        }

        public void RemoveFromCart(int id)
        {
            //Get the cart
            var cartItem = beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs.Single(
                cart => cart.WinkelwagenId == shoppingCartId
                && cart.Id == id);

            if (cartItem != null)
            {
                if (cartItem.Aantal > 1)
                {
                    cartItem.Aantal--;
                }
                else
                {
                    beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs.DeleteOnSubmit(cartItem);
                }
                beeldBankDB.SubmitChanges();
            }
        }

        public void EmptyCart()
        {
            var cartItems = beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs
                .Where(cart => cart.WinkelwagenId == shoppingCartId);

            foreach (var cartItem in cartItems)
            {
                beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs.DeleteOnSubmit(cartItem);
            }

            beeldBankDB.SubmitChanges();
        }

        public List<BEELDBANK_ORDERREGEL_WINKELWAGEN> GetCartItems()
        {
            var cartItems = (from cart in beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs
                             where cart.WinkelwagenId == shoppingCartId
                             select cart).ToList();
            return cartItems;
        }

        public int GetCount()
        {
            int? count = (from cartItems in beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs
                          where cartItems.WinkelwagenId == shoppingCartId
                          select (int?)cartItems.Aantal).Sum();

            return count ?? 0;
        }

        public decimal GetTotal()
        {
            decimal? total =
                (from cartItems in beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs
                 where cartItems.WinkelwagenId == shoppingCartId
                 select (int?)cartItems.Aantal).Sum(); //* cartItems.BEELDBANK_MEDIAOBJECT.Price)

            return total ?? decimal.Zero;
        }

        public int CreateOrder(BEELDBANK_ORDER order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();

            //Iterate the items in the cart, adding Order Details for each
            foreach (var cartItem in cartItems)
            {
                var orderDetails = new BEELDBANK_ORDERREGEL
                {
                    MediaId = cartItem.MediaId,
                    OrderId = order.Id,
                    //UnitPrice = cartItem.Album.Price
                };

                beeldBankDB.BEELDBANK_ORDERREGELs.InsertOnSubmit(orderDetails);

                orderTotal += Convert.ToDecimal(cartItem.Aantal); // * cartItem.Album.Price
            }

            //Save the order
            beeldBankDB.SubmitChanges();

            //Empty the shopping cart
            EmptyCart();

            //Return the OrderId as a confirmation number
            return order.Id;
        }

        // We're using HttpContextBase to allow access to cookies.
        public String GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    // User is logged in, associate the cart with there username
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid Class
                    Guid tempCartId = Guid.NewGuid();

                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }

        // When a user has logged in, migrate their shopping cart to
        // be associated with their username
        public void MigrateCart(string userName)
        {
            var shoppingCart = beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs
                .Where(c => c.WinkelwagenId == shoppingCartId);

            foreach (BEELDBANK_ORDERREGEL_WINKELWAGEN item in shoppingCart)
            {
                item.WinkelwagenId = userName;
            }
            beeldBankDB.SubmitChanges();
        }


        public void SaveShoppingCartToOrder(HttpRequestBase Request)
        {
            // Create a new shoppingcart order
            BEELDBANK_ORDER order = new BEELDBANK_ORDER();

            // Get the ShoppingcartID (unique user name) of the current user
            String naam = this.shoppingCartId;

            // Select the shoppingcart items for the current user
            var winkelWagenRegels = from ww in beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs where ww.WinkelwagenId == naam select ww;

            // itterate trough the shoppingcart items and add each item to an order row, while deleting it from the orriginal table
            foreach (var winkelWagenRegel in winkelWagenRegels)
            {
                var orderRegel = new BEELDBANK_ORDERREGEL();

                orderRegel.Aantal = winkelWagenRegel.Aantal;
                orderRegel.Afwerking = winkelWagenRegel.Afwerking;
                orderRegel.createdat = DateTime.Now;
                orderRegel.createdby = winkelWagenRegel.WinkelwagenId;
                orderRegel.Formaat = winkelWagenRegel.Formaat;
                orderRegel.MediaId = winkelWagenRegel.MediaId;
                orderRegel.MediaTypeId = winkelWagenRegel.MediaTypeId;
                orderRegel.modifiedat = DateTime.Now;
                orderRegel.modifiedby = winkelWagenRegel.WinkelwagenId;
                orderRegel.Type = winkelWagenRegel.Type;

                // add order to order row
                order.BEELDBANK_ORDERREGELs.Add(orderRegel);

                // Remove item from shoppingcart
                beeldBankDB.BEELDBANK_ORDERREGEL_WINKELWAGENs.DeleteOnSubmit(winkelWagenRegel);
            }

            // Fill aditional order information
            order.createdat = DateTime.Now;
            order.createdby = this.shoppingCartId;
            order.modifiedat = DateTime.Now;
            order.modifiedby = this.shoppingCartId;
            order.BestelDatum = DateTime.Now;
            order.OpdrachtNr = Request["opdrachtNumemr"];
            order.Gebruik = Request["gebruikMateriaal"];
            order.Opmerkingen = Request["opmerkingen"];

            MembershipUser user = Membership.GetUser(naam);

            // Calculate discount
            if (user.Email.Contains("rws.nl"))
                order.TotaalPrijs = (decimal)(PriceCalculator.priceItemsInShoppingCartByName(naam).uiteindelijkeBestelKosten * 0.5);
            else
                order.TotaalPrijs = (decimal)PriceCalculator.priceItemsInShoppingCartByName(naam).uiteindelijkeBestelKosten;

            // Get the userId (uniqueidentifier) from the user table
            order.UserId = userRep.FindOnesGuidByName(this.shoppingCartId);

            // Insert the new order
            beeldBankDB.BEELDBANK_ORDERs.InsertOnSubmit(order);

            // commit all changes
            beeldBankDB.SubmitChanges();
            
            // send confirmation mail
            Email.mailOrder(user, order);
        }

    }
}